package com.mspbots.cw.amqp.receivers;

import com.fasterxml.jackson.databind.JsonNode;
import com.mspbots.cw.amqp.BaseReceiver;
import com.mspbots.cw.amqp.model.Board;
import com.mspbots.cw.amqp.model.BoardAssociations;
import com.mspbots.cw.amqp.model.ExceptionLog;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Optional;

/**
 * BoardReceiver is com.mspbots.cw.amqp.receivers
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2020/2/24
 */
@Log4j2
@Component
@RequiredArgsConstructor
public class BoardReceiver extends BaseReceiver {

    @RabbitListener(queues = "wise.board")
    public void processBoard(Board board) {
        try{
            Optional<Long> id = this.databaseClient.execute("select id from tenant_board " +
                    "where tenant_id =:tenantId and cw_id =:cwId")
                    .as(Long.class)
                    .bind("tenantId", board.getTenantId())
                    .bind("cwId", board.getCwId())
                    .fetch().one().blockOptional(Duration.ofSeconds(10));
            if (id.isPresent() && id.get() > 0) {
                log.debug("Receiver connect wise tenant id:{},cw id:{},Board update id:{}",
                        board.getTenantId(), board.getCwId(), board.getId());
                board.setId(id.get());
                board.setSyncTime(LocalDateTime.now());
                this.databaseClient.update().table(Board.class).using(board).fetch().rowsUpdated().subscribe();
            } else {
                this.databaseClient.insert().into(Board.class).using(board).fetch().rowsUpdated().subscribe();
            }
//        super.messagingTemplate.convertAndSend("next-ticket.redis.board",board);
        }catch (Exception e){
            this.databaseClient.insert().into(ExceptionLog.class).using(
                    ExceptionLog.builder()
                            .tenantId(board.getTenantId().intValue())
                            .name("wise.board")
                            .status(500)
                            .type("wise.board")
                            .msg(e.getMessage()+","+objectMapper.convertValue(board, JsonNode.class).toString() )
                            .build()
            ).fetch().rowsUpdated().block(Duration.ofSeconds(10));
        }
    }

    @RabbitListener(queues = "wise.board.associations")
    public void processBoardAssociations(JsonNode associationsNode) {
        try{
            BoardAssociations associations = BoardAssociations.builder()
                    .cwId(associationsNode.get("id").asInt())
                    .boardId(associationsNode.get("boardId").asInt())
                    .tenantId(associationsNode.get("tenantId").asInt())
                    .typeId(!ObjectUtils.isEmpty(associationsNode.get("type"))?associationsNode.get("type").get("id").asInt():null)
                    .typeName(!ObjectUtils.isEmpty(associationsNode.get("type"))?associationsNode.get("type").get("name").asText():null)
                    .subTypeId(!ObjectUtils.isEmpty(associationsNode.get("subType"))?associationsNode.get("subType").get("id").asInt():null)
                    .subTypeName(!ObjectUtils.isEmpty(associationsNode.get("subType"))?associationsNode.get("subType").get("name").asText():null)
                    .itemId(!ObjectUtils.isEmpty(associationsNode.get("item"))?associationsNode.get("item").get("id").asInt():null)
                    .itemName(!ObjectUtils.isEmpty(associationsNode.get("item"))?associationsNode.get("item").get("name").asText():null)
                    .extend(associationsNode)
                    .build();

            Optional<Long> id = this.databaseClient.execute("select id from tenant_board_associations " +
                    " where tenant_id =:tenantId and cw_id =:cwId")
                    .as(Long.class)
                    .bind("tenantId", associations.getTenantId())
                    .bind("cwId", associations.getCwId())
                    .fetch().one().blockOptional(Duration.ofSeconds(10));

            if (id.isPresent() && id.get() > 0) {
                log.debug("Receiver connect wise tenant id:{},cw id:{},Board Associations update id:{}",
                        associations.getTenantId(), associations.getCwId(), associations.getId());
                associations.setId(id.get());
                associations.setSyncTime(LocalDateTime.now());
                this.databaseClient.update().table(BoardAssociations.class).using(associations).fetch().rowsUpdated().block();
            } else {
                this.databaseClient.insert().into(BoardAssociations.class).using(associations).fetch().rowsUpdated().block();
            }

//        associations.setExtend(null);
//        super.messagingTemplate.convertAndSend("next-ticket.redis.associations",associations);
        }catch (Exception e){
            if (!ObjectUtils.isEmpty(associationsNode.get("tenantId"))){
                this.databaseClient.insert().into(ExceptionLog.class).using(
                        ExceptionLog.builder()
                                .tenantId(associationsNode.get("tenantId").asInt())
                                .name("core.schedules")
                                .status(500)
                                .type("core.schedules")
                                .msg(e.getMessage()+","+associationsNode.toString() )
                                .build()
                ).fetch().rowsUpdated().block(Duration.ofSeconds(10));
            }
        }

    }

}
